package com.ysd.lis.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.WkKnowledgeApprovalMapper;
import com.ysd.lis.mapper.WkKnowledgeCatalogMapper;
import com.ysd.lis.mapper.WkKnowledgeContentMapper;
import com.ysd.lis.mapper.WkKnowledgeMapper;
import com.ysd.lis.request.KnowledgePageParam;
import com.ysd.lis.service.WkKnowledgeApprovalService;
import com.ysd.lis.util.ListToTreeUtil;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2024-03-04
 */
@Service
@Slf4j
public class WkKnowledgeApprovalServiceImpl extends ServiceImpl<WkKnowledgeApprovalMapper, WkKnowledgeApproval> implements WkKnowledgeApprovalService {

    @Autowired
    WkKnowledgeApprovalMapper wkKnowledgeApprovalMapper;
    @Autowired
    WkKnowledgeContentMapper wkKnowledgeContentMapper;
    @Autowired
    WkKnowledgeCatalogMapper wkKnowledgeCatalogMapper;
    @Autowired
    WkKnowledgeMapper wkKnowledgeMapper;

    @Override
    public Result findContentApprovalTree(KnowledgePageParam param) {

        List<Map> rList = new ArrayList<>();
        //获取需要审批得知识库数据
        //0未审批 5审批未通过 10 审批通过
        LambdaQueryWrapper<WkKnowledgeApproval> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WkKnowledgeApproval::getDelFlag,0)
                .eq(WkKnowledgeApproval::getStatus,0);

        List<WkKnowledgeApproval> approvalList = wkKnowledgeApprovalMapper.selectList(queryWrapper);
        if(ToolsUtils.isNotEmpty(approvalList)){
            List<String> collectIds = approvalList.stream().map(WkKnowledgeApproval::getContentId).distinct().collect(Collectors.toList());
            //查出需要审批得内容
            LambdaQueryWrapper<WkKnowledgeContent> queryWrapperC = new LambdaQueryWrapper<>();
            queryWrapperC.eq(WkKnowledgeContent::getDelFlag,0)
                    .in(WkKnowledgeContent::getId,collectIds)
                    .orderByAsc(WkKnowledgeContent::getSeq);
            List<WkKnowledgeContent> contentList = wkKnowledgeContentMapper.selectList(queryWrapperC);
            if(ToolsUtils.isNotEmpty(contentList)){
                List<Map> returnList = new ArrayList<>();

                //查出内容的目录
                List<String> catalogIds = contentList.stream().map(WkKnowledgeContent::getCatalogId).distinct().collect(Collectors.toList());

                LambdaQueryWrapper<WkKnowledgeCatalog> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WkKnowledgeCatalog::getDelFlag,0)
                        .in(WkKnowledgeCatalog::getId,catalogIds)
                        .orderByAsc(WkKnowledgeCatalog::getSeq);
                List<WkKnowledgeCatalog> catalogList = new ArrayList<>();
                 getAllKnowledgeCatalog(wkKnowledgeCatalogMapper.selectList(queryWrapper1),catalogList);
                //查出所有的知识
                List<String> knowledgeIds = contentList.stream().map(WkKnowledgeContent::getKnowledgeId).distinct().collect(Collectors.toList());

                LambdaQueryWrapper<WkKnowledge> queryWrapperK = new LambdaQueryWrapper<>();
                queryWrapperK.eq(WkKnowledge::getDelFlag,0)
                        .in(WkKnowledge::getId,knowledgeIds)
                        .orderByAsc(WkKnowledge::getSeq);
                List<WkKnowledge> knowledgeList = wkKnowledgeMapper.selectList(queryWrapperK);
                //生成属性结构数据
                for (WkKnowledgeCatalog catalog : catalogList) {
                    Map<String, Object> map = new HashMap();
                    map.put("id", catalog.getId());
                    map.put("knowledgeId", catalog.getKnowledgeId());
                    map.put("pid", catalog.getPid());
                    map.put("name", catalog.getName());
                    map.put("code", catalog.getCode());
                    map.put("seq", catalog.getSeq());
                    map.put("orgId", catalog.getOrgId());
                    map.put("status", catalog.getStatus());
                    map.put("knType", "catalog");
                    returnList.add(map);
                }

                for (WkKnowledgeContent content : contentList) {
                    Map<String, Object> map = new HashMap();
                    map.put("id", content.getId());
                    map.put("knowledgeId", content.getKnowledgeId());
                    map.put("pid", content.getCatalogId());
                    map.put("catalogId", content.getCatalogId());
                    map.put("orgId", content.getOrgId());
                    map.put("name", content.getTitle());
                    map.put("title", content.getTitle());
                    //map.put("content",content.getContent());
                    map.put("seq", content.getSeq());
                    map.put("status", content.getStatus());
                    map.put("publishTime", content.getPublishTime());
                    map.put("knType", "content");
                    returnList.add(map);
                }

                JSONArray objects = ListToTreeUtil.forObjectAndLevelToTree(returnList, "0", "id", "pid", "children", 1);

                List<JSONObject> list = objects.toList(JSONObject.class);
                for(WkKnowledge knowledge : knowledgeList){
                    Map<String, Object> map = new HashMap();
                    List<JSONObject> jsonObjects = list.stream().filter(ob -> ob.get("knowledgeId").equals(knowledge.getId())).collect(Collectors.toList());

                    map.put("id", knowledge.getId());
                    map.put("name", knowledge.getName());
                    map.put("code", knowledge.getCode());
                    map.put("knType", "knowledge");
                    map.put("level", 0);
                    map.put("children", jsonObjects);
                    rList.add(map);
                }
            }
        }
        return Result.succ(1, "查询成功", rList);
    }

    @Override
    public Result getContentAndApprovaByContentId(KnowledgePageParam param) {


        MPJLambdaWrapper<WkKnowledgeContent> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper
                .distinct()
                .selectAll(WkKnowledgeContent.class)
                .selectCollection(WkKnowledgeIssue.class, WkKnowledgeContent::getWkKnowledgeIssueList)
                .leftJoin(WkKnowledgeIssue.class, WkKnowledgeIssue::getContentId, WkKnowledgeContent::getId)
                .eq(WkKnowledgeContent::getDelFlag, 0)
                .eq(WkKnowledgeContent::getId, param.getContentId())
                .orderByAsc(WkKnowledgeContent::getSeq);
        WkKnowledgeContent wkKnowledgeContent = wkKnowledgeContentMapper.selectJoinOne(WkKnowledgeContent.class, mpjLambdaWrapper);
       //获取当前审核数据
        LambdaQueryWrapper<WkKnowledgeApproval> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WkKnowledgeApproval::getDelFlag,0)
                .eq(WkKnowledgeApproval::getStatus,0)
                .eq(WkKnowledgeApproval::getContentId,param.getContentId());
        WkKnowledgeApproval approval = this.getOne(queryWrapper);
        wkKnowledgeContent.setApproval(approval);
        return Result.succ(1, "查询成功！", wkKnowledgeContent);
    }

    @Override
    public Result submitApproval(WkKnowledgeApproval approval) {

        WkKnowledgeContent content = wkKnowledgeContentMapper.selectById(approval.getContentId());
        WkKnowledgeContent updateContent = new WkKnowledgeContent();
        //wkKnowledgeContentMapper
        //0未审批 5审批未通过 10 审批通过
        Integer status = approval.getStatus();
        if(status==10){
            updateContent.setContent(approval.getTempContent());
            updateContent.setTempContent(approval.getTempContent());
            updateContent.setId(content.getId());
            //新建/暂存0 ;未通过1 ;提交5 ;审核通过10  11 再次审核不通过  15再次提交 20再次审核通过
            if(content.getStatus().equals(new BigDecimal("5"))){
                updateContent.setStatus(new BigDecimal(10));
            }else if(content.getStatus().equals(new BigDecimal("15"))){
                updateContent.setStatus(new BigDecimal(20));
            }

        }else if(status==5){
            updateContent.setTempContent(approval.getTempContent());
            updateContent.setId(content.getId());
            if(content.getStatus().equals(new BigDecimal("5"))){
                updateContent.setStatus(new BigDecimal(1));
            }else if(content.getStatus().equals(new BigDecimal("15"))){
                updateContent.setStatus(new BigDecimal(11));
            }
        }
        int i = wkKnowledgeContentMapper.updateById(updateContent);
        if(i>0){
            approval.setApprovalTime(updateContent.getEditTime());
            wkKnowledgeApprovalMapper.updateById(approval);
        }
        return Result.succ(1, "审核完成", null);
    }

    @Override
    public Result findApprovalListByContentId(KnowledgePageParam param) {

        MPJLambdaWrapper<WkKnowledgeApproval> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(WkKnowledgeApproval.class)
                .selectAs("approval", SysUser::getRealname, WkKnowledgeApproval::getApprovalorName)
                .selectAs("submitter", SysUser::getRealname, WkKnowledgeApproval::getSubmitterName)
                .leftJoin(SysUser.class, "approval", SysUser::getId, WkKnowledgeApproval::getApprovalor)
                .leftJoin(SysUser.class, "submitter", SysUser::getId, WkKnowledgeApproval::getSubmitter)
                .eq(WkKnowledgeApproval::getDelFlag,0)
                .eq(WkKnowledgeApproval::getContentId,param.getContentId())
                .orderByAsc(WkKnowledgeApproval::getSubmitTime);
        List<WkKnowledgeApproval> approvalList = this.list(queryWrapper);
        return Result.succ(1, "查询成功", approvalList);
    }

    private void getAllKnowledgeCatalog(List<WkKnowledgeCatalog>  list,List<WkKnowledgeCatalog>  allList) {
        allList.addAll(list);
        List<String> pids = list.stream().map(WkKnowledgeCatalog::getPid).collect(Collectors.toList());
        List<WkKnowledgeCatalog> wkKnowledgeCatalogs = wkKnowledgeCatalogMapper.selectBatchIds(pids);
        if(ToolsUtils.isNotEmpty(wkKnowledgeCatalogs)){
            getAllKnowledgeCatalog(wkKnowledgeCatalogs,allList);
        }

    }
}
